<template>
    <el-drawer v-model="isShow" direction="rtl" :destroy-on-close="true" :size="550">
        <template #header>
            <h2 class="title">{{ title }}</h2>
        </template>

        <template #default>
            <schema-form ref="schemaFormRef" :schema="components[name]?.schema" v-loading="loading" :model="dtoModel" />
        </template>

        <template #footer>
            <el-button type="primary" @click="save">
                {{ saveBtnText }}
            </el-button>
        </template>
    </el-drawer>
</template>

<script setup>
import { ref, inject } from 'vue';
import { ElNotification } from 'element-plus';
import $curl from '$common/curl';
import schemaForm from '$widget/schema-form/schema-form.vue'

const { components, api } = inject('schemaViewData');
const emit = defineEmits(['command']);

const schemaFormRef = ref(null)
const name = ref('editForm');
const title = ref('')
const loading = ref(false)
const saveBtnText = ref('')
const mainKey = ref('')
const mainValue = ref('')
const dtoModel = ref({})

const isShow = ref(false);
const show = (rowData) => {
    const { config } = components.value[name.value]
    title.value = config.title
    saveBtnText.value = config.saveBtnText
    mainKey.value = config.mainKey // 主键
    mainValue.value = rowData[config.mainKey]
    dtoModel.value = {}
    isShow.value = true;

    fetchFormData()
}

const close = () => {
    isShow.value = false;
}

const fetchFormData = async () => {
    if (loading.value) {
        return;
    }
    loading.value = true
    const res = await $curl({
        method: 'get',
        url: api.value,
        query: {
            [mainKey.value]: mainValue.value
        }
    })
    loading.value = false
    if (!res.success || !res.data) {
        return
    } 
    dtoModel.value = res.data
}

const save = async () => {
    if (!schemaFormRef.value.validate()) { return; }

    loading.value = true;
    const res = await $curl({
        method: 'put',
        url: api.value,
        data: {
            [mainKey.value]: mainValue.value,
            ...schemaFormRef.value.getValue()
        }
    });
    loading.value = false;

    if (!res.success ) {
        return
    }
    ElNotification.success({
        title: '更新成功',
        message: res.msg || '更新成功',
        type: 'success'
    })
    close()
    emit('command', 'loadTableData')
}

defineExpose({
    name,
    show
});
</script>

<style lang="less" scoped></style>